import React, {useContext, useRef, useEffect, useCallback} from 'react';
import {View, ScrollView, FlatList} from 'react-native';
import dayjs from 'dayjs';
import Toast from 'react-native-root-toast';
import {useNavigation} from '@react-navigation/native';
import {useDebounceEffect, useMount, useUnmount, useSafeState} from 'ahooks';
import {Text, Button, Input, Dialog, ListItem, Avatar} from '@rneui/themed';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import {useSelector, useDispatch} from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import GlobalContext from '@/GlobalContext';
import ImagePicker from 'react-native-image-crop-picker';
import fileExtension from 'file-extension';
import {ApiHost, OssHost} from '@/config/common';
import {setKeyGetAccountInfo} from '@/store';
import DocumentPicker from 'react-native-document-picker';

const leftIconSize = 18;
const rightIconSize = 20;

import HeaderStyle1 from '@/components/HeaderStyle1';
import globalStyle from '@/style/global.less';

import RNFS from 'react-native-fs';
import RNFetchBlob from 'react-native-blob-util';
import {Dirs, FileSystem} from 'react-native-file-access';
import putFileToOss from '@/fun/putFileToOss';
import {round} from 'lodash';
import Dir from './Dir';
import File from './File';
import style from './style.less';
import UpdateSDcardDir from './UpdateSDcardDir';
import getDirsInfoSystem from './getDirsInfoSystem';
import updateFileToLocalDb from './updateFileToLocalDb';
export default () => {
  const {eventEmitterGlobal, localMongoDbFileSystem} =
    useContext(GlobalContext);

  const navigation = useNavigation();
  const dispatch = useDispatch();
  const token = useSelector(state => state.token.value);
  const accountInfo = useSelector(state => state.accountInfo.value);
  let defaultUri = accountInfo?.j_ext_info?.photo_relative_path;
  if (defaultUri) {
    defaultUri = `${OssHost}/${defaultUri}`;
  }
  let defDirPath = Dirs.SDCardDir;
  // defDirPath = '/sdcard/img163';
  const [dirPath, setDirPath] = useSafeState();
  useMount(() => {
    (async () => {
      const strV = await AsyncStorage.getItem('eventEmitterGlobalData');
      const json = JSON.parse(strV || '{}');
      const {netdiskOpenDirPath} = json;
      setDirPath(netdiskOpenDirPath || defDirPath);
    })();
  });

  const [dirArr, setDirArr] = useSafeState([]);
  const [allFileArr, setAllFileArr] = useSafeState([]);
  const refScrollView = useRef();

  const updDirArr = (dp = '') => {
    try {
      const arr = dp.split('/').filter(item => !!item);
      setDirArr(arr);
    } catch (e) {}
  };

  const getFilesInfoByMongoDb = async ({pPath = ''}) => {
    let docs = [];
    try {
      const db = localMongoDbFileSystem;
      const m = db
        .find({pPath: pPath})
        // .sort({sort: -1, name: 1})
        .skip(0)
        .limit(100000)
        .exec();
      docs = await m;
    } catch (e) {}
    return docs;
  };

  const updFilesInfoToMongoDb = async ({pPath = ''}) => {
    const docs = await getDirsInfoSystem({pPath: pPath});
    try {
      const db = localMongoDbFileSystem;
      const delRes = await db.removeAsync({pPath: pPath}, {multi: true});
      await db.insertAsync(docs);
    } catch (e) {
      console.log('updFilesInfoToMongoDb.异常', e.message);
    }
  };

  const updAllFileArr = async (dp = '') => {
    const start = dayjs();
    setAllFileArr([]);
    console.log('begin:', start.format());
    // let allFiles = await getFilesInfoByMongoDb({pPath: dp});
    // if (allFileArr.length === 0) {
    //   setAllFileArr([]);
    //   await updFilesInfoToMongoDb({pPath: dp});
    //   allFiles = await getFilesInfoByMongoDb({pPath: dp});
    //   console.log('Get files from system', allFiles.length);
    // } else {
    //   setTimeout(() => {
    //     updFilesInfoToMongoDb({pPath: dp});
    //   }, 3500);
    // }

    let allFiles = await getDirsInfoSystem({pPath: dp});

    setAllFileArr(allFiles);
    console.log('allFiles.length', allFiles.length);
    // const statDir = await FileSystem.statDir(dp);
    // console.log('statDir', statDir);

    const end = dayjs();
    console.log('  end:', end.format(), 'use', end.diff(start, 'ms'), 'ms');
  };

  const updEEGlobalData = async (pPath = '') => {
    try {
      const strV = await AsyncStorage.getItem('eventEmitterGlobalData');
      const json = JSON.parse(strV || '{}');
      json.netdiskOpenDirPath = pPath;
      await AsyncStorage.setItem(
        'eventEmitterGlobalData',
        JSON.stringify(json),
      );
    } catch (e) {
      console.log('updEEGlobalData.异常', e.message);
    }
  };

  useEffect(() => {
    if (!dirPath) {
      return;
    }
    updDirArr(dirPath);
    updAllFileArr(dirPath);
    updEEGlobalData(dirPath);

    setTimeout(() => {
      refScrollView.current.scrollToEnd({animated: false});
    }, 50);
  }, [dirPath]);

  useMount(() => {
    eventEmitterGlobal.on('SliceGoBack', async ({type}) => {
      if (type === 'GO_BACK') {
        try {
          const strV = await AsyncStorage.getItem('eventEmitterGlobalData');
          const json = JSON.parse(strV || '{}');
          const {netdiskOpenDirPath: str} = json;
          const arr = str.split('/').filter(item => !!item);
          if (!arr || arr.length <= 1) {
            navigation.pop();
          } else {
            arr.pop();
            const newPath = '/' + arr.join('/');
            setDirPath(newPath);
          }
        } catch (e) {
          console.log('异常', e.message);
        }
      }
    });
  });
  useUnmount(() => {
    eventEmitterGlobal.removeListener('SliceGoBack');
  });

  const showList = allFileArr
    .filter(item => item.type === 'directory')
    .concat(allFileArr.filter(item => item.type !== 'directory'));

  const [updateFileSystemDoing, setUpdateFileSystemDoing] = useSafeState(false);
  const [pInfo, setPInfo] = useSafeState({});
  const [percent, setPercent] = useSafeState();

  const updFSys = async () => {
    setUpdateFileSystemDoing(true);
    await updateFileToLocalDb({
      db: localMongoDbFileSystem,
      progress: info => {
        const {i, t, p, path, sMB, total} = info;
        console.log(`${i}/${t}: ${p}%`, path, total, sMB);
        // setPInfo(info);
        setPercent(p);
      },
    });
    setUpdateFileSystemDoing(false);
    setPercent(undefined);
  };
  return (
    <>
      <View
        style={{
          flex: 1,
        }}>
        <HeaderStyle1
          headerRight={() => (
            <View
              style={{
                marginRight: 10,
                minWidth: 80,
              }}>
              <Button
                title="更新"
                size="sm"
                onPress={updFSys}
                disabled={updateFileSystemDoing}
                // loading={updateFileSystemDoing}
              />
            </View>
          )}>
          设置备份目录
        </HeaderStyle1>
        <Dialog isVisible={updateFileSystemDoing} onBackdropPress={() => {}}>
          <Text>
            {percent > 0
              ? `正在更新目录信息 ${percent}% `
              : '正在扫描文件系统....'}
          </Text>
          <Dialog.Loading />
        </Dialog>
        <View style={style.box}>
          <View style={style.header}>
            <Text
              style={style.headerFirst}
              onPress={() => {
                const newPath = Dirs.SDCardDir;
                setDirPath(newPath);
              }}>
              {dirArr[0]}
            </Text>
            <ScrollView horizontal={true} ref={refScrollView}>
              {dirArr.map(
                (item, index, array) =>
                  (index && (
                    <View key={index} style={style.headerItem}>
                      <FontAwesome5
                        name="angle-right"
                        size={18}
                        style={style.headerItemIcon}
                      />
                      <Text
                        numberOfLines={1}
                        ellipsizeMode="tail"
                        onPress={async () => {
                          let newPath = '';
                          dirArr.forEach((dirName, sonIndex) => {
                            if (sonIndex <= index) {
                              newPath += `/${dirName}`;
                            }
                          });
                          setDirPath(newPath);
                        }}
                        style={[style.headerItemTxt]}>
                        {item}
                      </Text>
                    </View>
                  )) || <Text key={index}></Text>,
              )}
            </ScrollView>
          </View>

          <FlatList
            data={showList}
            renderItem={({item, index, separators}) => {
              if (item.type === 'directory') {
                return (
                  <Dir
                    item={item}
                    index={index}
                    setOpenDirPath={newDirPath => {
                      setDirPath(newDirPath);
                    }}
                  />
                );
              } else {
                return <File item={item} index={index} />;
              }
            }}
          />
        </View>
      </View>
    </>
  );
};
